package cn.zhx.xa.system.service.impl;
import cn.zhx.xa.model.dto.role_menu.AssignMenuDto;
import cn.zhx.xa.model.entity.SysRoleMenu;
import cn.zhx.xa.model.vo.menu.SysMenuSearchVo;
import cn.zhx.xa.system.dao.SysRoleMenuDao;
import cn.zhx.xa.system.service.SysMenuService;
import cn.zhx.xa.system.service.SysRoleMenuService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        //查询所有的菜单数据
        List<SysMenuSearchVo> sysMenuList = sysMenuService.findNodes() ;

        // 查询当前角色的菜单数据
        List<Long> roleMenuIds = sysRoleMenuDao.findSysRoleMenuByRoleId(roleId);

        // 将数据存储到Map中进行返回
        Map<String , Object> result = new HashMap<>() ;
        result.put("sysMenuList" , sysMenuList) ;
        result.put("roleMenuIds" , roleMenuIds) ;

        // 返回
        return result;
    }

    @Override
    @Transactional
    public void doAssign(AssignMenuDto assignMenuDto) {
        // 根据角色的id删除其所对应的菜单数据
        Long roleId = assignMenuDto.getRoleId();
        sysRoleMenuDao.deleteByRoleId(roleId);

        // 获取菜单的id集合
        List<Map<String, Number>> menuInfo = assignMenuDto.getMenuIdList();
        if(menuInfo != null && menuInfo.size() > 0) {
            menuInfo.forEach(map -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(map.get("id").longValue());
                sysRoleMenu.setIsHalf(map.get("isHalf").intValue());
                sysRoleMenuDao.save(sysRoleMenu);
            });

        }
    }
}
